package com.sunny.shop.service;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.sunny.shop.core.LocalUser;
import com.sunny.shop.core.enumeration.BaseType;
import com.sunny.shop.dto.CollectDTO;
import com.sunny.shop.model.Collect;
import com.sunny.shop.model.Riddle;
import com.sunny.shop.repository.CollectRepository;
import com.sunny.shop.repository.RiddleRepository;
import com.sunny.shop.vo.RiddleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RiddleServiceImpl {
    @Autowired
    private CollectRepository collectRepository;

    @Autowired
    private RiddleRepository riddleRepository;

    public List<RiddleVO> getRiddles(Long cateId){
        Long uid = LocalUser.getUser().getId();
        ArrayList<Long> ids = collectRepository.selectorderby(uid, 4, 1);
        PageRequest page = PageRequest.of(0, 50);
        List<Riddle> riddles = riddleRepository.selectByLimit(cateId, page);
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();
        ArrayList<RiddleVO> riddleVO = new ArrayList<>();
        riddles.forEach(r->{
            RiddleVO vo = new RiddleVO();
            mapper.map(r, vo);
            if(ids.contains(r.getId())){
                vo.setStatus(true);
            }else{
                vo.setStatus(false);
            }
            riddleVO.add(vo);
        });
        return riddleVO;
    }

    public boolean addCollect(Long id){
        Long uid = LocalUser.getUser().getId();
        Collect collect = collectRepository.findOneByCollectTypeAndTopicIdAndUid(BaseType.Riddle.getValue(), id, uid);
        Date now = new Date();
        if(collect == null){
            byte status = 1;
            CollectDTO build = CollectDTO.builder()
                    .collectType(BaseType.Riddle.getValue())
                    .topicId(id)
                    .status(status)
                    .uid(uid)
                    .createTime(now)
                    .build();
            Collect collectModel = new Collect();
            BeanUtils.copyProperties(build, collectModel);
            this.collectRepository.save(collectModel);
        }else{
            Integer status = collect.getStatus() == 1 ? 0 : 1;
            this.collectRepository.updateStatus(status,BaseType.Riddle.getValue(), id,uid);
        }
        return true;
    }
}
